package com.atguigu.yygh.hosp.config;

import com.atguigu.yygh.model.hosp.Department;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.IndexOperations;

/**
 * @author 孔德成
 * @slogan 致敬大师，致敬未来的你
 * @date 2021/9/3 10:48 上午
 * @desc
 */
@Configuration
public class MongoDbConfig {
    private final MongoTemplate mongoTemplate;

    public MongoDbConfig(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @EventListener(ApplicationReadyEvent.class)
    public void initIndicesAfterStartup() {
        // 手动创建索
        IndexOperations hospitalIndexOps = mongoTemplate.indexOps(Hospital.class);
        // 创建唯一索引
        hospitalIndexOps.ensureIndex(new Index().unique().on("hoscode", Sort.Direction.ASC));
        // 创建普通索引
        hospitalIndexOps.ensureIndex(new Index().on("hosname", Sort.Direction.ASC));

        // 为科室手动创建索引
        IndexOperations departmentIndexOps = mongoTemplate.indexOps(Department.class);
        departmentIndexOps.ensureIndex(new Index().on("hoscode", Sort.Direction.ASC));
        departmentIndexOps.ensureIndex(new Index().unique().on("depcode", Sort.Direction.ASC));


        // 为排班手动创建索引
        IndexOperations scheduleIndexOps = mongoTemplate.indexOps(Schedule.class);
        scheduleIndexOps.ensureIndex(new Index().on("hoscode", Sort.Direction.ASC));
        scheduleIndexOps.ensureIndex(new Index().on("depcode", Sort.Direction.ASC));
        // 排班编号
        scheduleIndexOps.ensureIndex(new Index().on("hosScheduleId", Sort.Direction.ASC));

    }
}
